package com.gator.desig_mode.interpreter;


import java.util.HashMap;
import java.util.Stack;

/**
 * @author 何章怀晓 hezhanghuaixiao
 * @version V1.0
 * @desc 计算器类 , 将map中的键值对解析并执行+-操作
 */
public class Calculator {


  private Expression expression;

  public Calculator(String expStr) {

    //运算先后顺序,使用栈
    Stack<Expression> stack = new Stack<>();
    //将表达式拆分成字符数组
    char[] chars = expStr.toCharArray();

    Expression left = null;
    Expression right = null;

    for (int i = 0; i < chars.length; i++) {
      switch (chars[i]) {
        case '+':
          left = stack.pop();//弹栈
          right = new VarExpression(String.valueOf(chars[++i]));
          stack.push(new AddExpression(left, right)); //将左右两端字符压栈
          break;
        case '-':
          left = stack.pop();
          right = new VarExpression(String.valueOf(chars[++i]));
          stack.push(new SubExpression(left, right));
          break;
        default:
          //压栈，既不是+-，那么肯定是key  如 a
          stack.push(new VarExpression(String.valueOf(chars[i])));
          break;
      }
    }
    this.expression = stack.pop();
  }

  public int run(HashMap<String,Integer> var){
    return this.expression.interpreter(var);
  }
}
